<template>
  <PerfectTableComponent
    v-bind="$props"
    v-model:multipleSelection="multipleSelection"
    :loadTableList="loadTableList"
    :changePageSize="changePageSize"
    :changePage="changePage"
    :removeQueryField="removeQueryField"
    :clearQuery="clearQuery"
    v-model:query="query"
    title="汽车商品"
    ref="tableRef"
    :queryFormHeaders="queryFormHeaders"
    :table="table"
    :tableColumns="tableColumns"
    :showTableIndex="false"
    :operatorColumnWidth="300"
    :baseUrl="urls.API_URL_BACKSTAGE_SHOP_CARPRODUCT"
    v-model:form="form"
    :formHeader="formHeader"
    dialogWidth="1000"
    formLabelWidth="120px"
    @beforeAddRow="beforeAddRow"
    @afterLoadDataSuccessInEditRow="afterLoadDataSuccessInEditRow"
    @beforeFormSubmit="beforeFormSubmit"
  >
    <!-----------------------------表格自定义列1----------------------------------------->
    <!--标题图片-->
    <template #table_column_coverImageUrl="scope: any">
      <PictureComponent :picUrl="scope.row.coverImage != null ? scope.row.coverImage.fileHttpUrl : ''" :noPicUrl="noPhotoSrc" />
    </template>
    <!--所属车型配置-->
    <template #table_column_carModelConfigName="scope: any">
      {{ scope.row.carModelConfig != null ? scope.row.carModelConfig.name : '' }}
    </template>
    <!--创建者-->
    <template #table_column_creatorName="scope: any">
      {{ scope.row.creator != null ? scope.row.creator.nickName : '' }}
    </template>
    <!--编辑者-->
    <template #table_column_editorName="scope: any">
      {{ scope.row.editor != null ? scope.row.editor.nickName : '' }}
    </template>
    <!--表单提交的自定义内容 -->
    <template #dialog_form_carModelConfigId>
      <!-- 车型配置选择框 -->
      <CarModelConfigSelectComponent
        v-model="form['carModelConfigId']"
        v-model:name="form['carModelConfigName']"
        :readonly="carModelConfigSelectComponentReadOnly"
        @afterClickSelectButton="tableRef.clearFieldValidation('carModelConfigId')"
        @closed="tableRef.fieldValidation('carModelConfigId')"
        @afterSelect="afterSelectCarModelConfig"
      />
    </template>
  </PerfectTableComponent>
</template>

<script setup lang="ts">
import PerfectTableComponent from '@/components/base/table/PerfectTableComponent.vue';
import CarModelConfigSelectComponent from '@/components/mes/CarModelConfigSelectComponent.vue';
import { onMounted, provide, reactive, ref } from 'vue';
import useTableList from '@/api/hooks/useTableList';
import type { FormHeader, ResponseData, TableColumn } from '@/types/interface/base_interface';
import urls from '@/api/request/urls';
import { getDict } from '@/api/dict';
import type { CarModelConfig } from '@/types/interface/mes_interface';
import type { CarProduct } from '@/types/interface/shop_interface';
import Request from '@/api/request/request';
import { noPhotoSrc } from '@/api/pic';

// 表格工具必备参数
const { table, query, loadTableList, removeQueryField, clearQuery, changePageSize, changePage } = useTableList(
  urls.API_URL_BACKSTAGE_SHOP_CARPRODUCT
);
// 将表格刷新函数传到子容器
provide('loadTableList', loadTableList);

// 复选框选择的记录row集合，提供给父组件调用，例如在这个表格上用对话框再进行封装。
const multipleSelection = defineModel<any[]>('multipleSelection', {
  required: false,
  default: []
});
// 接收父组件（因为本组件供其他组件调用，因此封装）传递过来的值
interface Props {
  showToolBar?: Boolean; // 是否显示表格工具栏，默认显示
  showOperatorColumn?: Boolean; // 是否显示表格右侧的操作栏，默认显示
  showAddNewButton?: Boolean; // 在表格工具栏是否显示新增按钮
  showDeleteButton?: Boolean; // 是否显示删除按钮，如果不显示则整个表格插件都不显示
  showEditButton?: Boolean; //  是否显示编辑按钮，如果不显示则整个表格插件都不显示
  operatorColumnWidth?: number; // 表格右侧操作了大小
  dialogConfirmButtonText?: string; // 确认按钮上的文字
}
const props = withDefaults(defineProps<Props>(), {
  showToolBar: () => Boolean(true), //默认显示
  operatorColumnWidth: 300
});

//查询==========================================================
const queryFormHeaders = ref<FormHeader[]>([]);

//表格==========================================================
// 表格插件ref对象
const tableRef = ref();

//表格列
// 定义表格所有的列字段信息
const tableColumns = ref<TableColumn[]>([]);

//表单==========================================================
//表单对象
const form = ref<CarProduct>({});
//表单元素类型
const formHeader = ref<FormHeader[]>([]);

const getCarBrands = async () => {
  const resData: any = await new Request(urls.API_URL_BACKSTAGE_MES_CARBRAND + '/all').get();
  if (resData.success) {
    return resData.data;
  }
};
const getCarModels = async () => {
  const resData: any = await new Request(urls.API_URL_BACKSTAGE_MES_CARMODEL + '/all').get();
  if (resData.success) {
    return resData.data;
  }
};
onMounted(async () => {
  //获取汽车品牌列表
  const carBrands = await getCarBrands();
  //获取汽车车型列表
  const carModels = await getCarModels();
  //汽车类型
  const carTypeDict = await getDict('汽车类型', 'string');
  //商品上架状态
  const onSaleDict = await getDict('商品上架状态', 'boolean');
  //汽车类型
  const orderNumDict = await getDict('商品优先级', 'number');
  queryFormHeaders.value = [
    // 查询表单
    {
      prop: 'name',
      label: '名称'
    },
    // {
    //   prop: 'carBrandId',
    //   propAsName: 'carModel.carBrand.id',
    //   label: '汽车品牌',
    //   type: 'selectObject',
    //   list: carBrands,
    //   config: {
    //     valueKey: 'id',
    //     defaultProp: {
    //       value: 'id',
    //       label: 'name'
    //     }
    //   }
    // },
    {
      prop: 'carModelConfig.id',
      label: '车型配置',
      type: 'selectRemote',
      width: '200px',
      url: urls.API_URL_BACKSTAGE_MES_CARMODELCONFIG,
      queryNameForUrl: 'name',
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: '{name}'
        }
      }
    },
    {
      prop: 'onSale',
      label: '上架状态',
      type: 'select',
      list: onSaleDict
    }
  ];
  //表格对象
  tableColumns.value = [
    {
      label: '名称',
      prop: 'name',
      fixed: true,
      width: 250
    },
    {
      label: '封面图片',
      prop: 'coverImageUrl',
      type: 'custom',
      width: 100
    },
    {
      label: '车型配置',
      prop: 'carModelConfigName',
      type: 'custom',
      width: 150
    },
    {
      label: '指导价',
      prop: 'originalPrice',
      width: 150
    },
    {
      label: '现价',
      prop: 'originalPrice',
      width: 150
    },
    {
      label: '库存',
      prop: 'repository',
      width: 150
    },
    {
      label: '上架状态',
      prop: 'onSale',
      width: 100,
      type: 'switch',
      dict: onSaleDict
    },
    {
      label: '优先级',
      prop: 'orderNum',
      width: 100,
      type: 'dict',
      dict: orderNumDict
    },
    {
      label: '发布者',
      prop: 'creatorName',
      type: 'custom',
      width: 150
    },
    {
      label: '创建时间',
      prop: 'createTime',
      width: 180
    },
    {
      label: '编辑者',
      prop: 'editorName',
      type: 'custom',
      width: 150
    },
    {
      label: '最后编辑时间',
      prop: 'updateTime',
      width: 180
    }
  ];
  // 添加编辑表单
  formHeader.value = [
    {
      label: '车型配置',
      prop: 'carModelConfigId',
      type: 'custom',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      prop: 'coverImageId',
      label: '标题图片',
      type: 'photoSelect',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '名称',
      prop: 'name',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        },
        {
          min: 1,
          max: 50,
          message: '长度在 1 到 50个字符',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '指导价',
      prop: 'originalPrice',
      type: 'number',
      width: '250px',
      config: {
        number: {
          precision: 2,
          min: 0.01,
          max: 9999999999.99,
          prefix: '￥',
          suffix: '元'
        }
      },
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '优惠价',
      prop: 'price',
      type: 'number',
      width: '250px',
      config: {
        number: {
          precision: 2,
          min: 0.01,
          max: 9999999999.99,
          prefix: '￥',
          suffix: '元'
        }
      },
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '库存',
      prop: 'repository',
      type: 'number',
      width: '250px',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        },
        {
          type: 'number',
          min: 0,
          message: '不能小于0'
        }
      ]
    },
    {
      label: '优先级',
      prop: 'orderNum',
      type: 'select',
      list: orderNumDict,
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '是否上架',
      prop: 'onSale',
      type: 'switch',
      list: onSaleDict,
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '商品简介',
      prop: 'description',
      type: 'textarea',
      rules: [
        {
          max: 255,
          message: '长度不能超过255个字符',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '详细描述',
      prop: 'content',
      type: 'editor',
      config: {
        wangeditor: {
          editorPlaceholder: '请输入商品的详细信息'
        }
      }
    }
  ];
});
//设置添加和编辑表单中的车型配置选择组件只读状态。
// 处理逻辑：添加的时候可以正常选择，编辑的时候是只读状态，因为汽车工艺编辑不允许切换车型配置。
const carModelConfigSelectComponentReadOnly = ref<boolean>(false);
//在添加行的动作以前
const beforeAddRow = async () => {
  //传入初始值
  form.value = {
    onSale: false,
    orderNum: 100
  };
};
//在编辑行读取后端记录后需要修改的地方
const afterLoadDataSuccessInEditRow = async (formEdit: CarProduct) => {
  //重新封装表单对象的值
  if (formEdit.carModelConfig != null) {
    formEdit.carModelConfigId = formEdit.carModelConfig.id;
    formEdit.carModelConfigName = formEdit.carModelConfig.name;
  }
  if (formEdit.coverImage != null) {
    formEdit.coverImageId = formEdit.coverImage.id;
  }
  //注意，如果富文本初始传入的值是null，则会错误。因此为了避免后端传入null，这里要做处理
  if (form.value.description === null) {
    form.value.description === '';
  }
};
//在表单提交前对对象进行封装
const beforeFormSubmit = () => {
  if (form.value.carModelConfigId != null) {
    form.value.carModelConfig = {
      id: form.value.carModelConfigId
    };
  }
  if (form.value.coverImageId != null && form.value.coverImageId.length > 0) {
    form.value.coverImage = {
      id: form.value.coverImageId
    };
  }
};
//在选择汽车配置后
const afterSelectCarModelConfig = async (carmodelconfigs: CarModelConfig[]) => {
  //将当前选择的汽车配置返回
  if (carmodelconfigs.length > 0) {
    //获取汽车配置
    form.value.carModelConfig = carmodelconfigs[0];
    //根据选择的汽车配置生成其他字段信息，方便操作。
    if (form.value.carModelConfig) {
      form.value.name = `${form.value.carModelConfig.carModel?.name}${form.value.carModelConfig.name}`;
    }
  }
};
//清空表格选中的复选框
const clearSelection = () => tableRef.value!.clearSelection();
defineExpose({
  clearSelection,
  clearQuery,
  loadTableList
});
</script>

<style scoped></style>
